import { createApp } from 'vue'
import App from './App.vue'
import { initRouter } from './features/router/router'
import { initStore } from './features/store/store'
import { initDeviceId } from '@/utils/qiankunProps'

import './assets/base.less'
import './assets/MoonIcon/style.css'

import {
  renderWithQiankun,
  qiankunWindow,
  QiankunProps,
} from 'vite-plugin-qiankun/dist/helper'
import './public-path'

// const app = createApp(App)

// initRouter(app)
// initStore(app)
// app.mount('#app')

const app = () => createApp(App)
let appCopy = null

// 挂载函数
function render(props: any) {
  const appInstance = app()
  appCopy = appInstance

  const { container } = props
  initRouter(appInstance)
  initStore(appInstance)
  // 这个ID为index.html中div的ID名称
  appInstance.mount(container ? container.querySelector('#app') : '#app')
}

renderWithQiankun({
  mount(props: QiankunProps) {
    props.onReady('resource pool')
    initDeviceId(props?.deviceId)

    // @ts-ignore
    props.onGlobalStateChange((state, prev) => {
      initDeviceId(state?.deviceId)
    })

    render(props)

    // 在vue全局注册主应用的状态监听和状态改变事件
    // app.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange;
    // app.config.globalProperties.$setGlobalState = props.setGlobalState;

    // app.config.globalProperties.mainRouter = props.mainRouter
  },
  bootstrap() {
    console.log('bootstrap')
  },
  unmount() {
    console.log('unmount')
    appCopy.unmount()
  },
  update() {
    console.log('update')
  },
})

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({})
}
